<template>
    <div class="article-list-container" ref="article-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
                >
                <ArticleItem
                    v-for="(article, index) in articles"
                    :key="index"
                    :article="article"
                />
            </van-list>
        </van-pull-refresh>
    </div>
</template>
<script>
import * as Api from 'api/common';
import ArticleItem from 'com/common/articleItem';
import { debounce } from 'lodash';

export default {
    name: 'articleList',
    components: {
        ArticleItem
    },
    props: {
        channel: {
            type: Object,
            require: true
        }
    },
    data () {
        return {
            articles: [],
            loading: false,
            finished: false,
            preTimestamp: undefined,
            refreshing: false,
            scrollTop: 0
        };
    },
    methods: {
        async onLoad (flag = false) {
            const params = {
                channel_id: this.channel.id,
                timestamp: this.preTimestampnew || Date.now(),
                with_top: 1
            };
            const res = await Api.reqDev('/v1_1/articles', 'get', {
                params
            });
            let { results } = res.data;
            if (res.message === 'OK') {
                if (flag) {
                    this.articles.unshift(...results);
                    this.$toast(`刷新成功${results.length}条数据`);
                    this.refreshing = false;
                } else this.articles.push(...results);
            }
            this.loading = false;
            if (results.length) { // 当前页面数据不为空，下一页可能还有数据
                this.preTimestamp = res.data.pre_timestamp;
            } else this.finished = true;
        },
        onRefresh() {
            // 清空列表数据
            this.finished = false;
            // 讲查询时间重置
            this.preTimestamp = undefined;
            // 重新加载数据
            // 将 loading 设置为 true，表示处于加载状态
            this.loading = true;
            this.onLoad(true);
        },
        setScorll () {
            this.$nextTick(() => {
                this.$refs['article-list'].scrollTop = this.scrollTop;
            });
        }
    },
    mounted () {
        const articleList = this.$refs['article-list'];
        articleList.onscroll = debounce(() => {
            this.scrollTop = articleList.scrollTop;
        }, 50);
    },
    activated () {
        this.$refs['article-list'].scrollTop = this.scrollTop;
    }
};
</script>
<style lang="less" scoped>
.article-list-container {
    position: fixed;
    right: 0;
    left: 0;
    top: 92px;
    bottom: 55px;
    overflow-y: auto;
}
</style>
